package com.xuhuan.practice.controller;

import com.xuhuan.practice.dto.user.UserInfoDTO;
import com.xuhuan.practice.dto.user.UserLoginDTO;
import com.xuhuan.practice.dto.user.UserRegisterDTO;
import com.xuhuan.practice.dto.user.UserUpdateInfoDTO;
import com.xuhuan.practice.dto.user.UserUpdatePwdDTO;
import com.xuhuan.practice.entity.User;
import com.xuhuan.practice.response.Result;
import com.xuhuan.practice.service.UserService;
import com.xuhuan.practice.utils.CurrentUserUtil;
import com.xuhuan.practice.utils.JwtUtil;
import com.xuhuan.practice.utils.Md5Util;
import com.xuhuan.practice.utils.RedisUtil;
import com.xuhuan.practice.validator.group.AddGroup;
import com.xuhuan.practice.validator.group.UpdateGroup;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: huan.xu
 * @create: 2024/6/10 11:30
 * @description:
 **/
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  private UserService userService;

  /**
   * 注册
   *
   * @param userRegisterDTO
   * @return
   */
  @PostMapping("/register")
  public Result register(@RequestBody @Validated(AddGroup.class) UserRegisterDTO userRegisterDTO) {
    User queryUser = userService.getUserByUserName(userRegisterDTO.getUsername());
    if (queryUser != null) {
      return Result.error("用户名已被占用");
    } else {
      userService.register(userRegisterDTO.getUsername(), userRegisterDTO.getPassword());
      return Result.success("注册成功");
    }
  }

  /**
   * 登录
   *
   * @param userLoginDTO
   * @return
   */
  @PostMapping("/login")
  public Result login(@RequestBody @Validated UserLoginDTO userLoginDTO) {
    User queryUser = userService.getUserByUserName(userLoginDTO.getUsername());
    if (queryUser == null) {
      return Result.error("用户名或错误");
    }
    if (Md5Util.md5String(userLoginDTO.getPassword()).equals(queryUser.getPassword())) {
      Map<String, Object> claims = new HashMap<>();
      claims.put("id", queryUser.getId());
      claims.put("username", queryUser.getUsername());
      String token = JwtUtil.genToken(claims);
      // token存入redis中
      RedisUtil.setJWTStringKey(token, token);
      return Result.success(token);
    }
    return Result.error("用户名或错误");
  }

  /**
   * 获取用户信息
   *
   * @return
   */
  @GetMapping("/userInfo")
  public Result<UserInfoDTO> userInfo() {
    User user = userService.getUserByUserName(CurrentUserUtil.getCurrentUserName());
    UserInfoDTO userInfoDTO = new UserInfoDTO();
    BeanUtils.copyProperties(user, userInfoDTO);
    return Result.success(userInfoDTO);
  }

  /**
   * 修改用户信息
   *
   * @return
   */
  @PutMapping("/update")
  public Result update(
      @RequestBody @Validated(UpdateGroup.class) UserUpdateInfoDTO userUpdateInfoDTO) {
    userService.update(userUpdateInfoDTO);
    return Result.success();
  }

  /**
   * 更新用户头像
   *
   * @return
   */
  @PutMapping("/updateAvatar")
  public Result updateAvatar(@RequestParam @NotBlank(message = "用户头像不能为空") String userPic) {
    userService.updateUserPic(userPic);
    return Result.success();
  }

  /**
   * 更新用户密码
   *
   * @return
   */
  @PatchMapping("/updatePwd")
  public Result updatePwd(@RequestBody @Validated UserUpdatePwdDTO updatePwdDTO,
      @RequestHeader("Authorization") String token) {
    if (!StringUtils.hasLength(updatePwdDTO.getOldPwd())
        || !StringUtils.hasLength(updatePwdDTO.getNewPwd())
        || !StringUtils.hasLength(updatePwdDTO.getRePwd())) {
      return Result.error("缺少必要的参数");
    }
    User loginUser = userService.getUserByUserName(CurrentUserUtil.getCurrentUserName());
    if (!loginUser.getPassword().equals(Md5Util.md5String(updatePwdDTO.getOldPwd()))) {
      return Result.error("原密码不正确");
    }

    if (!updatePwdDTO.getNewPwd().equals(updatePwdDTO.getRePwd())) {
      return Result.error("两次填写的新密码不一致");
    }

    userService.updatePwd(updatePwdDTO.getNewPwd());
    // 删除redis中原有的token
    RedisUtil.delKey(token);
    return Result.success();
  }
}
